#include "graficobarras.h"

GraficoBarras::GraficoBarras( vector<float>& dados, QWidget* parent) : QGLWidget(parent){
	setWindowIcon(QIcon(QPixmap ( QString("images/histogram.png") )));
	
	this->dados = dados;
	
	width = 300;
	height = 200;
	
	larguraBarras = 0.9*width/(float)(dados.size());
	
	
	vector<float>::iterator it = dados.begin();
	valorMaximo = dados[0];
	valorMinimo = 0;
	
	while( it != dados.end() ){
		if( *it > valorMaximo ){
			valorMaximo = *it;
		}
		if( *it < valorMinimo ){
			valorMinimo = *it;
		}
		++it;
	}
	
	resize(width,height);
	show();
	
}

float GraficoBarras::scaleValue(float value, float min, float max, float newMin, float newMax){
	return ((newMax-newMin)*(value-min))/(max-min) + newMin;
}

void GraficoBarras::drawRectangle( int x0, int y0, int x1, int y1 ){
	glBegin(GL_POLYGON);
		glVertex2f(x0, y0);
		glVertex2f(x1, y0);
		glVertex2f(x1, y1);
		glVertex2f(x0, y1);
	glEnd();
}

void GraficoBarras::initializeGL()	{
	glMatrixMode( GL_PROJECTION );
	gluOrtho2D( 0, width, 0, height );
	glMatrixMode( GL_MODELVIEW );
	
}

void GraficoBarras::resizeGL( int w, int h ){
	GLdouble largura, altura;

	if( h == 0 ) h = 1;
	
	largura = w;
	altura = h;
	
	glViewport( 0, 0, largura, altura );
	
	glMatrixMode( GL_PROJECTION );
	glLoadIdentity();
	
	if( largura <= altura ){
		gluOrtho2D( 0, width, 0, height*(altura/largura) );
	}
	else{
		gluOrtho2D( 0, width, 0, height );
	}
}

void GraficoBarras::paintGL(){
	
	glClearColor(1,1,1,0);

	glClear( GL_COLOR_BUFFER_BIT );
	
	float zero = scaleValue( 0, valorMinimo, valorMaximo, 0.05*height, 0.9*height );
	
	vector<float>::iterator it = dados.begin();
	int cont = 0;
	while( it!= dados.end() ){
		
		float valorEscalado = scaleValue( *it, valorMinimo, valorMaximo, 0.05*height, 0.9*height );
		
		float x0 = cont*larguraBarras+0.05*width;
		float y0 = zero;
		float x1 = x0 + larguraBarras;
		float y1 = valorEscalado;
		
		glColor3f(1,0,0);
		
		drawRectangle( x0, y0, x1, y1 );
			
		++it;
		++cont;
	}
	
	glColor3f(0,0,0);
	
	glBegin(GL_LINES);
		glVertex2f(0.05*width,0.05*height);
		glVertex2f(0.05*width,0.95*height);
		glVertex2f(0.05*width,zero);
		glVertex2f(0.98*width,zero);
	glEnd();
	
}
		

 